package org.jeecgframework.web.tcdev.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.ComboTree;
import org.jeecgframework.core.common.model.json.TreeGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.vo.easyui.ComboTreeModel;
import org.jeecgframework.tag.vo.easyui.TreeGridModel;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.tcdev.entity.TArticleCategoryEntity;
import org.jeecgframework.web.tcdev.service.ArticleCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zjy on 2015/9/25.
 */
@Controller
@RequestMapping("/articleCategoryController")
public class ArticleCategoryController {
    @Autowired
    private ArticleCategoryService articleCategoryService;
    @Autowired
    private SystemService systemService;
    private String mes;
    /**
     * 视图
     */
    @RequestMapping(params = "view")
    public ModelAndView view(){
        return new ModelAndView("tcdev/articleCategory/categoryList");
    }
    /**
     * 新增或修改视图
     */
    @RequestMapping(params = "addorupdate")
    public ModelAndView view1(HttpServletRequest request,String id){
        if(StringUtil.isNotEmpty(id)){
            TArticleCategoryEntity tBcArticleCategoryEntity =  articleCategoryService.getEntity(TArticleCategoryEntity.class, id);

            request.setAttribute("category",tBcArticleCategoryEntity);

        }else{
            request.setAttribute("pid",request.getParameter("pid"));
        }
        return new ModelAndView("tcdev/articleCategory/addorupdate");
    }
    /**
     * 获取分类列表
     * @param request
     * @param response
     * @param
     * @param tBcArticleCategoryEntity
     */
    @RequestMapping(params = "datagrid")
    @ResponseBody
    public Object datagrid(HttpServletRequest request,HttpServletResponse response,TreeGrid treegrid,TArticleCategoryEntity tBcArticleCategoryEntity){
        CriteriaQuery cq = new CriteriaQuery(TArticleCategoryEntity.class);
        if("yes".equals(request.getParameter("isSearch"))){
            treegrid.setId(null);
            tBcArticleCategoryEntity.setId(null);
        }
        if(null != tBcArticleCategoryEntity.getTitle()){
            org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tBcArticleCategoryEntity);
        }
        if (treegrid.getId() != null) {
            cq.eq("tArticleCategoryEntity.id", treegrid.getId());
        }
        if (treegrid.getId() == null) {
            cq.eq("tArticleCategoryEntity.id","0");
//            cq.isNull("TBbPGoodsCategoryEntity");
        }
        cq.eq("deleted", 0);
        cq.add();
        List<TreeGrid> categoryList =null;
        categoryList=articleCategoryService.getListByCriteriaQuery(cq, false);
        if(categoryList.size()==0&&tBcArticleCategoryEntity.getTitle()!=null){
            cq = new CriteriaQuery(TArticleCategoryEntity.class);
            TArticleCategoryEntity parCategoryt = new TArticleCategoryEntity();
            tBcArticleCategoryEntity.settArticleCategoryEntity(parCategoryt);
            org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tBcArticleCategoryEntity);
            categoryList =articleCategoryService.getListByCriteriaQuery(cq, false);
        }
        List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
        TreeGridModel treeGridModel = new TreeGridModel();
        treeGridModel.setTextField("title");
        treeGridModel.setParentText("tArticleCategoryEntity_title");
        treeGridModel.setParentId("tArticleCategoryEntity_id");
        treeGridModel.setSrc("createTime");
        treeGridModel.setIdField("id");
        treeGridModel.setChildList("tArticleCategoryEntitys");
        Map<String,Object> fieldMap = new HashMap<String, Object>();
        //fieldMap.put("homeShow", "homeShow");
      //  fieldMap.put("sort", "sort");
        fieldMap.put("subtitle", "subtitle");
//        fieldMap.put("createTime","createTime");
        fieldMap.put("publishPlat", "publishPlat");
        treeGridModel.setFieldMap(fieldMap);
        treeGrids = articleCategoryService.treegrid(categoryList, treeGridModel);

        JSONArray jsonArray = new JSONArray();
        for (TreeGrid treeGrid : treeGrids) {

            jsonArray.add(JSON.parse(treeGrid.toJson()));
        }
        return jsonArray;
    }
    /**
     *
     * 文章分类树形下拉框
     * @param request
     * @param comboTree
     * @return
     */
    @RequestMapping(params = "setPFunction")
    @ResponseBody
    public List<ComboTree> setPFunction(HttpServletRequest request, ComboTree comboTree) {
        CriteriaQuery cq = new CriteriaQuery(TArticleCategoryEntity.class);
      /*  if(null != request.getParameter("selfId")){
            cq.notEq("id", request.getParameter("selfId"));
        }*/
        if (comboTree.getId() != null) {
            cq.eq("tArticleCategoryEntity.id", comboTree.getId());
        }
        if (comboTree.getId() == null) {
            cq.eq("tArticleCategoryEntity.id","0");
        }

       cq.eq("deleted",0);

        cq.add();
        List<TArticleCategoryEntity> goodsCategoryList = systemService.getListByCriteriaQuery(cq, false);
        List<ComboTree> comboTrees = new ArrayList<ComboTree>();
        ComboTreeModel comboTreeModel = new ComboTreeModel("id", "title", "tArticleCategoryEntitys");
        comboTrees = systemService.ComboTree(goodsCategoryList, comboTreeModel, null, true);

        return comboTrees;

    }

    /**
     * 保存文章分类
     * @param request
     * @param tArticleCategoryEntity
     * @return
     */
    @RequestMapping(params = "save")
    @ResponseBody
    public AjaxJson saveadd(HttpServletRequest request,TArticleCategoryEntity tArticleCategoryEntity){
        AjaxJson j = new AjaxJson();
        if(StringUtil.isEmpty(tArticleCategoryEntity.getId())){
            try{
                tArticleCategoryEntity.setDeleted(0);
                articleCategoryService.save(tArticleCategoryEntity);
                mes = "添加成功";
            }catch (Exception e){
                e.printStackTrace();
                mes = "添加文章分类失败";

            }

        }else {
            TArticleCategoryEntity t = articleCategoryService.getEntity(TArticleCategoryEntity.class, tArticleCategoryEntity.getId());
            try{

                MyBeanUtils.copyBeanNotNull2Bean(tArticleCategoryEntity, t);

                articleCategoryService.saveOrUpdate(t);
                mes = "修改【"+t.getTitle()+"】成功";
            }catch (Exception e){
                mes = "修改【"+t.getTitle()+"】失败";

            }

        }

        systemService.addLog(mes, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);

        j.setMsg(mes);
        return j;
    }

    /**
     * 删除文章分类
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(params = "delete")
    @ResponseBody
    public AjaxJson deleteCategory(String id,HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        int count = 0;
        try {
            List<TArticleCategoryEntity>  list = articleCategoryService.findHql(" from TArticleCategoryEntity where deleted = 0 and tArticleCategoryEntity.id = ?" , new Object[]{ id});
            count = list.size();
            if(count>0){
                mes = "您要删除的节点下面有子节点,不能删除";
            }else {
                TArticleCategoryEntity tArticleCategoryEntity =  articleCategoryService.getEntity(TArticleCategoryEntity.class, id);
                tArticleCategoryEntity.setDeleted(1);
                articleCategoryService.saveOrUpdate(tArticleCategoryEntity);
                mes = "删除成功分类【"+tArticleCategoryEntity.getTitle()+"】";
           }
        }catch (Exception e){
            if(count==0){
                mes = "文章分类删除失败";
            }else {
                mes = "您要删除的节点下面有子节点,不能删除";
            }

        }
        systemService.addLog(mes, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        j.setMsg(mes);
        return j;
    }
}
